{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#| default_exp models.softs"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#| hide\n",
    "%load_ext autoreload\n",
    "%autoreload 2"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#| hide\n",
    "import logging\n",
    "import warnings\n",
    "from fastcore.test import test_eq\n",
    "from nbdev.showdoc import show_doc\n",
    "from neuralforecast.common._model_checks import check_model"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# SOFTS\n",
    "\n",
    "SOFTS (Series-cOre Fused Time Series) incorporates the novel STar Aggregate-Dispatch (STAD) module. Instead of leearning channel interactions through a distributed architecture, like attention, the STAD module employs a centralized strategy where series are aggregated to form a global core representation, while maintaning linear complexity.\n",
    "\n",
    "**References**\n",
    "- [Lu Han, Xu-Yang Chen, Han-Jia Ye, De-Chuan Zhan. \"SOFTS: Efficient Multivariate Time Series Forecasting with Series-Core Fusion\"](https://arxiv.org/pdf/2404.14197)\n",
    "\n",
    "![Figure 1. Architecture of SOFTS.](imgs_models/softs_architecture.png)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#| export\n",
    "\n",
    "import torch\n",
    "import torch.nn as nn\n",
    "import torch.nn.functional as F\n",
    "\n",
    "from typing import Optional\n",
    "from neuralforecast.losses.pytorch import MAE\n",
    "from neuralforecast.common._base_model import BaseModel\n",
    "from neuralforecast.common._modules import TransEncoder, TransEncoderLayer"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 1. Auxiliary functions\n",
    "### 1.1 Embedding"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#| export\n",
    "class DataEmbedding_inverted(nn.Module):\n",
    "    \"\"\"\n",
    "    Data Embedding\n",
    "    \"\"\"    \n",
    "    def __init__(self, c_in, d_model, dropout=0.1):\n",
    "        super(DataEmbedding_inverted, self).__init__()\n",
    "        self.value_embedding = nn.Linear(c_in, d_model)\n",
    "        self.dropout = nn.Dropout(p=dropout)\n",
    "\n",
    "    def forward(self, x, x_mark):\n",
    "        x = x.permute(0, 2, 1)\n",
    "        # x: [Batch Variate Time]\n",
    "        if x_mark is None:\n",
    "            x = self.value_embedding(x)\n",
    "        else:\n",
    "            # the potential to take covariates (e.g. timestamps) as tokens\n",
    "            x = self.value_embedding(torch.cat([x, x_mark.permute(0, 2, 1)], 1))\n",
    "        # x: [Batch Variate d_model]\n",
    "        return self.dropout(x)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 1.2 STAD (STar Aggregate Dispatch)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#| export\n",
    "class STAD(nn.Module):\n",
    "    \"\"\"\n",
    "    STar Aggregate Dispatch Module\n",
    "    \"\"\"\n",
    "    def __init__(self, d_series, d_core):\n",
    "        super(STAD, self).__init__()\n",
    "\n",
    "\n",
    "        self.gen1 = nn.Linear(d_series, d_series)\n",
    "        self.gen2 = nn.Linear(d_series, d_core)\n",
    "        self.gen3 = nn.Linear(d_series + d_core, d_series)\n",
    "        self.gen4 = nn.Linear(d_series, d_series)\n",
    "\n",
    "    def forward(self, input, *args, **kwargs):\n",
    "        batch_size, channels, d_series = input.shape\n",
    "\n",
    "        # set FFN\n",
    "        combined_mean = F.gelu(self.gen1(input))\n",
    "        combined_mean = self.gen2(combined_mean)\n",
    "\n",
    "        # stochastic pooling\n",
    "        if self.training:\n",
    "            ratio = F.softmax(torch.nan_to_num(combined_mean), dim=1)\n",
    "            ratio = ratio.permute(0, 2, 1)\n",
    "            ratio = ratio.reshape(-1, channels)\n",
    "            indices = torch.multinomial(ratio, 1)\n",
    "            indices = indices.view(batch_size, -1, 1).permute(0, 2, 1)\n",
    "            combined_mean = torch.gather(combined_mean, 1, indices)\n",
    "            combined_mean = combined_mean.repeat(1, channels, 1)\n",
    "        else:\n",
    "            weight = F.softmax(combined_mean, dim=1)\n",
    "            combined_mean = torch.sum(combined_mean * weight, dim=1, keepdim=True).repeat(1, channels, 1)\n",
    "\n",
    "        # mlp fusion\n",
    "        combined_mean_cat = torch.cat([input, combined_mean], -1)\n",
    "        combined_mean_cat = F.gelu(self.gen3(combined_mean_cat))\n",
    "        combined_mean_cat = self.gen4(combined_mean_cat)\n",
    "        output = combined_mean_cat\n",
    "\n",
    "        return output, None"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 2. Model"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#| export\n",
    "\n",
    "class SOFTS(BaseModel):\n",
    "\n",
    "    \"\"\" SOFTS\n",
    "    \n",
    "    **Parameters:**<br>\n",
    "    `h`: int, Forecast horizon. <br>\n",
    "    `input_size`: int, autorregresive inputs size, y=[1,2,3,4] input_size=2 -> y_[t-2:t]=[1,2].<br>\n",
    "    `n_series`: int, number of time-series.<br>\n",
    "    `futr_exog_list`: str list, future exogenous columns.<br>\n",
    "    `hist_exog_list`: str list, historic exogenous columns.<br>\n",
    "    `stat_exog_list`: str list, static exogenous columns.<br>\n",
    "    `exclude_insample_y`: bool=False, whether to exclude the target variable from the input.<br>    \n",
    "    `hidden_size`: int, dimension of the model.<br>\n",
    "    `d_core`: int, dimension of core in STAD.<br>\n",
    "    `e_layers`: int, number of encoder layers.<br>\n",
    "    `d_ff`: int, dimension of fully-connected layer.<br>\n",
    "    `dropout`: float, dropout rate.<br>\n",
    "    `use_norm`: bool, whether to normalize or not.<br>\n",
    "    `loss`: PyTorch module, instantiated train loss class from [losses collection](https://nixtla.github.io/neuralforecast/losses.pytorch.html).<br>\n",
    "    `valid_loss`: PyTorch module=`loss`, instantiated valid loss class from [losses collection](https://nixtla.github.io/neuralforecast/losses.pytorch.html).<br>\n",
    "    `max_steps`: int=1000, maximum number of training steps.<br>\n",
    "    `learning_rate`: float=1e-3, Learning rate between (0, 1).<br>\n",
    "    `num_lr_decays`: int=-1, Number of learning rate decays, evenly distributed across max_steps.<br>\n",
    "    `early_stop_patience_steps`: int=-1, Number of validation iterations before early stopping.<br>\n",
    "    `val_check_steps`: int=100, Number of training steps between every validation loss check.<br>\n",
    "    `batch_size`: int=32, number of different series in each batch.<br>\n",
    "    `valid_batch_size`: int=None, number of different series in each validation and test batch, if None uses batch_size.<br>\n",
    "    `windows_batch_size`: int=32, number of windows to sample in each training batch, default uses all.<br>\n",
    "    `inference_windows_batch_size`: int=32, number of windows to sample in each inference batch, -1 uses all.<br>\n",
    "    `start_padding_enabled`: bool=False, if True, the model will pad the time series with zeros at the beginning, by input size.<br>\n",
    "    `step_size`: int=1, step size between each window of temporal data.<br>\n",
    "    `scaler_type`: str='identity', type of scaler for temporal inputs normalization see [temporal scalers](https://nixtla.github.io/neuralforecast/common.scalers.html).<br>\n",
    "    `random_seed`: int=1, random_seed for pytorch initializer and numpy generators.<br>\n",
    "    `drop_last_loader`: bool=False, if True `TimeSeriesDataLoader` drops last non-full batch.<br>\n",
    "    `alias`: str, optional,  Custom name of the model.<br>\n",
    "    `optimizer`: Subclass of 'torch.optim.Optimizer', optional, user specified optimizer instead of the default choice (Adam).<br>\n",
    "    `optimizer_kwargs`: dict, optional, list of parameters used by the user specified `optimizer`.<br>\n",
    "    `lr_scheduler`: Subclass of 'torch.optim.lr_scheduler.LRScheduler', optional, user specified lr_scheduler instead of the default choice (StepLR).<br>\n",
    "    `lr_scheduler_kwargs`: dict, optional, list of parameters used by the user specified `lr_scheduler`.<br>\n",
    "    `dataloader_kwargs`: dict, optional, list of parameters passed into the PyTorch Lightning dataloader by the `TimeSeriesDataLoader`. <br>\n",
    "    `**trainer_kwargs`: int,  keyword trainer arguments inherited from [PyTorch Lighning's trainer](https://pytorch-lightning.readthedocs.io/en/stable/api/pytorch_lightning.trainer.trainer.Trainer.html?highlight=trainer).<br>\n",
    "    \n",
    "    **References**<br>\n",
    "    [Lu Han, Xu-Yang Chen, Han-Jia Ye, De-Chuan Zhan. \"SOFTS: Efficient Multivariate Time Series Forecasting with Series-Core Fusion\"](https://arxiv.org/pdf/2404.14197)\n",
    "    \"\"\"\n",
    "\n",
    "    # Class attributes\n",
    "    EXOGENOUS_FUTR = False\n",
    "    EXOGENOUS_HIST = False\n",
    "    EXOGENOUS_STAT = False\n",
    "    MULTIVARIATE = True\n",
    "    RECURRENT = False\n",
    "\n",
    "    def __init__(self,\n",
    "                 h,\n",
    "                 input_size,\n",
    "                 n_series,\n",
    "                 futr_exog_list = None,\n",
    "                 hist_exog_list = None,\n",
    "                 stat_exog_list = None,\n",
    "                 exclude_insample_y = False,\n",
    "                 hidden_size: int = 512,\n",
    "                 d_core: int = 512,\n",
    "                 e_layers: int = 2,\n",
    "                 d_ff: int = 2048,\n",
    "                 dropout: float = 0.1,\n",
    "                 use_norm: bool = True,\n",
    "                 loss = MAE(),\n",
    "                 valid_loss = None,\n",
    "                 max_steps: int = 1000,\n",
    "                 learning_rate: float = 1e-3,\n",
    "                 num_lr_decays: int = -1,\n",
    "                 early_stop_patience_steps: int =-1,\n",
    "                 val_check_steps: int = 100,\n",
    "                 batch_size: int = 32,\n",
    "                 valid_batch_size: Optional[int] = None,\n",
    "                 windows_batch_size = 32,\n",
    "                 inference_windows_batch_size = 32,\n",
    "                 start_padding_enabled = False,\n",
    "                 step_size: int = 1,\n",
    "                 scaler_type: str = 'identity',\n",
    "                 random_seed: int = 1,\n",
    "                 drop_last_loader: bool = False,\n",
    "                 alias: Optional[str] = None,\n",
    "                 optimizer = None,\n",
    "                 optimizer_kwargs = None,\n",
    "                 lr_scheduler = None,\n",
    "                 lr_scheduler_kwargs = None, \n",
    "                 dataloader_kwargs = None,           \n",
    "                 **trainer_kwargs):\n",
    "        \n",
    "        super(SOFTS, self).__init__(h=h,\n",
    "                                    input_size=input_size,\n",
    "                                    n_series=n_series,\n",
    "                                    futr_exog_list = futr_exog_list,\n",
    "                                    hist_exog_list = hist_exog_list,\n",
    "                                    stat_exog_list = stat_exog_list,\n",
    "                                    exclude_insample_y = exclude_insample_y,\n",
    "                                    loss=loss,\n",
    "                                    valid_loss=valid_loss,\n",
    "                                    max_steps=max_steps,\n",
    "                                    learning_rate=learning_rate,\n",
    "                                    num_lr_decays=num_lr_decays,\n",
    "                                    early_stop_patience_steps=early_stop_patience_steps,\n",
    "                                    val_check_steps=val_check_steps,\n",
    "                                    batch_size=batch_size,\n",
    "                                    valid_batch_size=valid_batch_size,\n",
    "                                    windows_batch_size=windows_batch_size,\n",
    "                                    inference_windows_batch_size=inference_windows_batch_size,\n",
    "                                    start_padding_enabled=start_padding_enabled,\n",
    "                                    step_size=step_size,\n",
    "                                    scaler_type=scaler_type,\n",
    "                                    random_seed=random_seed,\n",
    "                                    drop_last_loader=drop_last_loader,\n",
    "                                    alias=alias,\n",
    "                                    optimizer=optimizer,\n",
    "                                    optimizer_kwargs=optimizer_kwargs,\n",
    "                                    lr_scheduler=lr_scheduler,\n",
    "                                    lr_scheduler_kwargs=lr_scheduler_kwargs,\n",
    "                                    dataloader_kwargs=dataloader_kwargs,\n",
    "                                    **trainer_kwargs)\n",
    "        \n",
    "        self.h = h\n",
    "        self.enc_in = n_series\n",
    "        self.dec_in = n_series\n",
    "        self.c_out = n_series\n",
    "        self.use_norm = use_norm\n",
    "\n",
    "        # Architecture\n",
    "        self.enc_embedding = DataEmbedding_inverted(input_size, \n",
    "                                                    hidden_size, \n",
    "                                                    dropout)\n",
    "        \n",
    "        self.encoder = TransEncoder(\n",
    "            [\n",
    "                TransEncoderLayer(\n",
    "                    STAD(hidden_size, d_core),\n",
    "                    hidden_size,\n",
    "                    d_ff,\n",
    "                    dropout=dropout,\n",
    "                    activation=F.gelu\n",
    "                ) for l in range(e_layers)\n",
    "            ]\n",
    "        )\n",
    "\n",
    "        self.projection = nn.Linear(hidden_size, self.h * self.loss.outputsize_multiplier, bias=True)\n",
    "\n",
    "    def forecast(self, x_enc):\n",
    "        # Normalization from Non-stationary Transformer\n",
    "        if self.use_norm:\n",
    "            means = x_enc.mean(1, keepdim=True).detach()\n",
    "            x_enc = x_enc - means\n",
    "            stdev = torch.sqrt(torch.var(x_enc, dim=1, keepdim=True, unbiased=False) + 1e-5)\n",
    "            x_enc /= stdev\n",
    "\n",
    "        _, _, N = x_enc.shape\n",
    "        enc_out = self.enc_embedding(x_enc, None)\n",
    "        enc_out, attns = self.encoder(enc_out, attn_mask=None)\n",
    "        dec_out = self.projection(enc_out).permute(0, 2, 1)[:, :, :N]\n",
    "\n",
    "        # De-Normalization from Non-stationary Transformer\n",
    "        if self.use_norm:\n",
    "            dec_out = dec_out * (stdev[:, 0, :].unsqueeze(1).repeat(1, self.h * self.loss.outputsize_multiplier, 1))\n",
    "            dec_out = dec_out + (means[:, 0, :].unsqueeze(1).repeat(1, self.h * self.loss.outputsize_multiplier, 1))\n",
    "        return dec_out\n",
    "    \n",
    "    def forward(self, windows_batch):\n",
    "        insample_y = windows_batch['insample_y']\n",
    "\n",
    "        y_pred = self.forecast(insample_y)\n",
    "        y_pred = y_pred.reshape(insample_y.shape[0],\n",
    "                                self.h,\n",
    "                                -1)\n",
    "\n",
    "        return y_pred"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "show_doc(SOFTS)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "show_doc(SOFTS.fit, name='SOFTS.fit')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "show_doc(SOFTS.predict, name='SOFTS.predict')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#| hide\n",
    "# Unit tests for models\n",
    "logging.getLogger(\"pytorch_lightning\").setLevel(logging.ERROR)\n",
    "logging.getLogger(\"lightning_fabric\").setLevel(logging.ERROR)\n",
    "with warnings.catch_warnings():\n",
    "    warnings.simplefilter(\"ignore\")\n",
    "    check_model(SOFTS, [\"airpassengers\"])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 3. Usage example"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#| eval: false\n",
    "import pandas as pd\n",
    "import matplotlib.pyplot as plt\n",
    "\n",
    "from neuralforecast import NeuralForecast\n",
    "from neuralforecast.models import SOFTS\n",
    "from neuralforecast.utils import AirPassengersPanel, AirPassengersStatic\n",
    "from neuralforecast.losses.pytorch import MASE\n",
    "Y_train_df = AirPassengersPanel[AirPassengersPanel.ds<AirPassengersPanel['ds'].values[-12]].reset_index(drop=True) # 132 train\n",
    "Y_test_df = AirPassengersPanel[AirPassengersPanel.ds>=AirPassengersPanel['ds'].values[-12]].reset_index(drop=True) # 12 test\n",
    "\n",
    "model = SOFTS(h=12,\n",
    "              input_size=24,\n",
    "              n_series=2,\n",
    "              hidden_size=256,\n",
    "              d_core=256,\n",
    "              e_layers=2,\n",
    "              d_ff=64,\n",
    "              dropout=0.1,\n",
    "              use_norm=True,\n",
    "              loss=MASE(seasonality=4),\n",
    "              early_stop_patience_steps=3,\n",
    "              batch_size=32)\n",
    "\n",
    "fcst = NeuralForecast(models=[model], freq='ME')\n",
    "fcst.fit(df=Y_train_df, static_df=AirPassengersStatic, val_size=12)\n",
    "forecasts = fcst.predict(futr_df=Y_test_df)\n",
    "\n",
    "# Plot predictions\n",
    "fig, ax = plt.subplots(1, 1, figsize = (20, 7))\n",
    "Y_hat_df = forecasts.reset_index(drop=False).drop(columns=['unique_id','ds'])\n",
    "plot_df = pd.concat([Y_test_df, Y_hat_df], axis=1)\n",
    "plot_df = pd.concat([Y_train_df, plot_df])\n",
    "\n",
    "plot_df = plot_df[plot_df.unique_id=='Airline1'].drop('unique_id', axis=1)\n",
    "plt.plot(plot_df['ds'], plot_df['y'], c='black', label='True')\n",
    "plt.plot(plot_df['ds'], plot_df['SOFTS'], c='blue', label='Forecast')\n",
    "ax.set_title('AirPassengers Forecast', fontsize=22)\n",
    "ax.set_ylabel('Monthly Passengers', fontsize=20)\n",
    "ax.set_xlabel('Year', fontsize=20)\n",
    "ax.legend(prop={'size': 15})\n",
    "ax.grid()"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "python3",
   "language": "python",
   "name": "python3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
